//https://leetcode.cn/problems/evaluate-reverse-polish-notation/
package codeRandomThoughts.Test150逆波兰表达式求值;

import java.util.Stack;

public class Solution2 {
    /**
     * 二刷
     * 逆波兰表达式是一种后缀表达式,即运算符写在后面
     * 遇到数字则入栈
     * 遇到算符则取出栈顶两个数字进行计算
     * 并且将结果压入栈中
     *
     * @param tokens
     * @return
     */
    public int evalRPN(String[] tokens) {
        Stack<Integer> stack = new Stack<>();
        for (int i = 0; i < tokens.length; i++) {
            String token = tokens[i];
            //switch换成if其实效率要高很多
            switch (token) {
                case "+": {
                    Integer pop1 = stack.pop();
                    Integer pop2 = stack.pop();
                    stack.push(pop1 + pop2);
                    break;
                }
                case "-": {
                    Integer pop1 = stack.pop();
                    Integer pop2 = stack.pop();
                    stack.push(pop2 - pop1);
                    break;
                }
                case "*": {
                    Integer pop1 = stack.pop();
                    Integer pop2 = stack.pop();
                    stack.push(pop1 * pop2);
                    break;
                }
                case "/": {
                    Integer pop1 = stack.pop();
                    Integer pop2 = stack.pop();
                    stack.push(pop2 / pop1);
                    break;
                }
                default: {
                    stack.push(Integer.valueOf(token));
                    break;
                }
            }
        }
        return stack.pop();
    }
}
